package com.resource.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.resource.constant.OfficeApiConstants;
import com.resource.constant.RedisConstants;
import com.resource.redis.RedisUtil;
import com.resource.request.OfficeTokenRequest;
import com.resource.response.OfficeResponse;
import com.resource.response.OfficeTokenResponse;
import com.resource.service.OfficeTokenService;
import com.resource.utils.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @Author: xianggaoxiong
 * @Date: 2020-09-22 14:31
 **/
@Slf4j
@Service
public class OfficeTokenServiceImpl implements OfficeTokenService {
	@Resource
	private RedisUtil redisUtil;

	@Resource
	private RestTemplate restTemplate;
	@Value("${office.app.agent_id}")
	private String agentId;
	@Value("${office.app.secret}")
	private String secret;
	@Value("${office.app.user}")
	private String user;
	@Value("${office.api.url}")
	private String apiUrl;

	@Override
	public String getToken(String userId) {
		String userParam=StrUtil.isNotBlank(userId)?userId:user;
		Object token = redisUtil.get(String.format(RedisConstants.OFFICE_TOKEN,userParam));
		if (ObjectUtil.isNotEmpty(token)) {
			return String.valueOf(token);
		}
		String url = String.format(OfficeApiConstants.TOKEN_URL, apiUrl);
		OfficeTokenRequest request = OfficeTokenRequest.builder().agent_id(agentId).secret(secret).user(userParam).build();
		// 创建请求头
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_JSON);
		HttpEntity<OfficeTokenRequest> entity = new HttpEntity<OfficeTokenRequest>(request, headers);
		ResponseEntity<OfficeResponse> responseEntity = restTemplate.postForEntity(url, entity, OfficeResponse.class);
		log.info("【泛微】返回token信息：{}", ObjectUtil.toString(responseEntity));
		if (responseEntity.getStatusCode() == HttpStatus.OK) {
			if (ObjectUtil.isNull(responseEntity.getBody()) || ObjectUtil.isNull(responseEntity.getBody().getData())) {
				throw new RuntimeException("获取token失败");
			}
			OfficeTokenResponse convert = Convert.convert(OfficeTokenResponse.class,
					responseEntity.getBody().getData());
			redisUtil.set(String.format(RedisConstants.OFFICE_TOKEN,userParam), convert.getToken(), Long.valueOf(convert.getExpired_in())-600);
			return convert.getToken();
		} else {
			throw new ServiceException("获取token失败");
		}
	}

}
